/**
 * 
 */

package com.chengyu.eyc.interceptor;

import java.sql.Timestamp;
import java.util.Properties;

import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.springframework.stereotype.Component;

import com.chengyu.eyc.model.BaseModel;
import com.chengyu.eyc.service.EycBaseService;
import com.chengyu.eyc.utils.SpringUtil;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author kevin
 *
 */
@Slf4j
@Component
@Intercepts({@Signature(type = org.apache.ibatis.executor.Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public class EycMybatisInterceptor implements Interceptor {

    /**
     * @see org.apache.ibatis.plugin.Interceptor#intercept(org.apache.ibatis.plugin.Invocation)
     */
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        if (args != null && args.length >= 2 && args[1] instanceof BaseModel) {
            BaseModel baseModel = (BaseModel)args[1];
            baseModel.setUpdateTime(new Timestamp(System.currentTimeMillis()));
            EycBaseService eycBasicService = SpringUtil.getBean(EycBaseService.class);
            if (StrUtil.isBlank(baseModel.getUpdatePerson())) {
                baseModel.setUpdatePerson(StrUtil.isBlank(eycBasicService.getUserId()) ? "system" : eycBasicService.getUserId());
            }
            MappedStatement mappedStatement = (MappedStatement)args[0];
            SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
            if (sqlCommandType == SqlCommandType.INSERT) {
                baseModel.setCreateTime(new Timestamp(System.currentTimeMillis()));
                if (StrUtil.isBlank(baseModel.getCreatePerson())) {
                    baseModel.setCreatePerson(StrUtil.isBlank(eycBasicService.getUserId()) ? "system" : eycBasicService.getUserId());
                }
            } /*else if(sqlCommandType == SqlCommandType.UPDATE) {
              
              }*/
        }
        return invocation.proceed();
    }

    /**
     * @see org.apache.ibatis.plugin.Interceptor#plugin(java.lang.Object)
     */
    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    /**
     * @see org.apache.ibatis.plugin.Interceptor#setProperties(java.util.Properties)
     */
    @Override
    public void setProperties(Properties properties) {
        log.warn(properties.toString());
    }

}
